/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package wwcontroluiclient;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Date;

/**
 *
 * @author Michael Ferry
 */
public class WWControlClientCommThread extends Thread{
    private Socket WWControlServerSocket;
    private PrintWriter outToServer;
    private BufferedReader inFromServer;
    private WWControlUIClient WWUI;

    public WWControlClientCommThread(WWControlUIClient client_arg){
        super("WWControlCommThread");
        WWUI = client_arg;
    }
    public void SendMessage(String message){
        outToServer.println(message);
    }
    public void Disconnect(){
            outToServer.println("close");
    }
    public void run() {
        String fromServer, fromUser;
        try {
            System.out.println("Attempting to connect to server");
            WWControlServerSocket = new Socket("132.239.77.171", 4444);
            System.out.println("Connected to server");
            outToServer = new PrintWriter(WWControlServerSocket.getOutputStream(), true);
            inFromServer = new BufferedReader(new InputStreamReader(WWControlServerSocket.getInputStream()));
            
            //Get initial server status
            outToServer.println("s gs");
            while (!(fromServer = inFromServer.readLine()).equals("close")) {
                System.out.println(new Date() + "Server: " + fromServer);
                ParseServerInput(fromServer);

            }
            System.out.println("Server connection ended");
            outToServer.close();
            inFromServer.close();
            //stdIn.close();
            WWControlServerSocket.close();
        } catch (IOException e) {
            System.out.println(e);
        }
    }

    public void ParseServerInput(String input) {
        String delims = "[ ]+";
        String[] tokens = input.split(delims);

        //Determine if this is a control message
        if ("s".equals(tokens[0])) {
            if("data".equals(tokens[1])){
                WWUI.SetDataCollectionUIState(Boolean.parseBoolean(tokens[2]));
            }
            if("motor".equals(tokens[1])){
                WWUI.SetMotorControlUIState(Boolean.parseBoolean(tokens[2]));
            }
            else if("ifk".equals(tokens[1])){
                WWUI.SetIfkUIState(Integer.parseInt(tokens[2]),Boolean.parseBoolean(tokens[3]));
            }
        }
    }
    public void SetDataCollectionStateClient(boolean state, long DataCollectionIntervalMilliSeconds){
        this.SendMessage("c data " + state + " " + DataCollectionIntervalMilliSeconds);
    }
    public void SetMotorControlStateClient(boolean state, long MotorRunDurationMilli, long MotorRunPeriodMilli){
        this.SendMessage("c motor " + state + " " + MotorRunDurationMilli + " " + MotorRunPeriodMilli);
    }
}